<?php
/**
 * Created by PhpStorm.
 * User: LMtwo
 * Date: 2019/7/2
 * Time: 14:19
 */

namespace app\stage\controller;
use think\Db;
//微信自动回复类
class WX_Class
{
    protected $_weixin_token = 'wx9c5e747c9593ec2f';

    public function __construct($config = array())
    {
        if ($config)
        {
            foreach ($config as $key => $val)
            {
                if(isset($this->{'_' . $key}))
                {
                    $this->{'_' . $key} = $val;
                }
            }
        }
        $this->valid();

    }

    /**
     * 接入是否生效
     *
     * @return void
     */
    public function valid(){
        // 随机字符串
      //  $echostr = $_GET['echostr'];

         if ($this->_check_signature()){
           // if($echostr){
               // echo $echostr;//此处能打印字符，打印了的话会被微信认为是非法数据
               // exit;
           // }
        }else{
            exit('nonono');
        }
    }

    /**
     * 接收消息
     *
     * @return object 微信接口对象
     */
    public function msg()
    {
//        $post = $GLOBALS["HTTP_RAW_POST_DATA"]; php7 不可用
        $post = file_get_contents("php://input");
        if ( ! $post)
        {
            return;
        }
        $data = simplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA);
        $Event = $data->Event;

        if($Event == "subscribe")
        {
            $fromUsername = $data->FromUserName;
            $toUsername = $data->ToUserName;
            $c_user = Db::name('php_member0')->where(['openid' => $fromUsername])->find();
            if(!$c_user){
                $token = getToken();
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$fromUsername}&lang=zh_CN";
                $getUserinfo = https_request($url);
                $getUserinfo = json_decode($getUserinfo,true);
                $userinfo = [
                    'nickname' => $getUserinfo['nickname'],
                    'sex' => $getUserinfo['sex'],
                    'country' => $getUserinfo['country'],
                    'province' => $getUserinfo['province'],
                    'city' => $getUserinfo['city'],
                    'headimgurl' => $getUserinfo['headimgurl'],
                    'openid' => $getUserinfo['openid']
                ];
               Db::name('php_member0')->insert($userinfo);
            }
           /* $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";

            $MsgType = "text";
            $Content = "同学您好！欢迎关注\n\n发选修问题给我即可返回答案";
            $time = time();
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $MsgType, $Content);
            echo $resultStr;*/
        }
        return $data;
    }

    /**
     *  发送消息
     *
     * @param string $type text|news 消息类型
     * @param array $msg 消息
     * @param string $tag 0|1 星标消息
     */
    public function send($type = 'text', $msg = array(), $tag = 0)
    {
        if ( ! in_array($type, array('text', 'news')))
        {
            return;
        }

        // 文本消息
        if ($type == 'text')
        {
            $tpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
						<FuncFlag>%s</FuncFlag>
						</xml>";

            echo sprintf($tpl, $msg['to'], $msg['from'], $msg['time'], $type, $msg['content'], $tag);
        }else if ($type == 'news')
        {


            // 图文消息
            $tpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<ArticleCount>%s</ArticleCount>
						<Articles>";

            $output = sprintf($tpl, $msg['to'], $msg['from'], $msg['time'], $type, 1);
            $item = $msg['items'];
            $tpl = "<item>
						<Title><![CDATA[%s]]></Title>
						<Description><![CDATA[%s]]></Description>
						<PicUrl><![CDATA[%s]]></PicUrl>
						<Url><![CDATA[%s]]></Url>
						 </item>
						 </Articles>
    				</xml>";

            $output .= sprintf($tpl, $item['title'], trim($item['description']), $item['picurl'], $item['url']);

            echo $output;

        }
    }

    /**
     * 根据经纬度反译地理信息
     *
     * @param string $lat 纬度
     * @param string $lng 经度
     * @return array
     */
    public function geocode($lat, $lng, $language = 'en')
    {
        $url = sprintf('http://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&sensor=false&language=' . $language, $lat, $lng);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $geo = curl_exec($ch);
        curl_close($ch);

        $geo = json_decode($geo, TRUE);

        // 不存在有效地理信息
        if ( ! isset($geo['results']))
        {
            return;
        }

        $output = array();

        foreach ($geo['results'][0]['address_components'] as $address)
        {
            $output[$address['types'][0]] = $address['long_name'];
        }

        return $output;
    }

    /**
     * 通过检验signature对网址接入合法性进行校验
     *
     * @return bool
     */
    private function _check_signature()
    {
        // 微信加密签名
        $signature = $_GET['signature'];
        // 时间戳
        $timestamp = $_GET['timestamp'];
        // 随机数
        $nonce = $_GET['nonce'];

        $tmp = array($this->_weixin_token, $timestamp, $nonce);
        sort($tmp, SORT_STRING);

        $str = sha1(implode($tmp));

        return $str == $signature ? TRUE : FALSE;
    }
}
